package com.chj.design.handler;

import lombok.Data;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Data
@Component
public class ChainPatternDemo {

    //自动注入各个责任链的对象
    @Resource
    private List<AbstractHandler> abstractHandlers;

    private AbstractHandler firstAbstractHandler;

    //spring注入后自动执行，责任链的对象连接起来
    @PostConstruct
    public void initializeChainFilter() {
        for (int i = 0; i < abstractHandlers.size(); i++) {
            if (i == 0) {
                firstAbstractHandler = abstractHandlers.get(0);
            } else {
                AbstractHandler currentHander = abstractHandlers.get(i - 1);
                AbstractHandler nextHander = abstractHandlers.get(i);
                currentHander.setNextHandler(nextHander);
            }
        }
    }

    //直接调用这个方法使用
    public String exec(String request, String response) {
        firstAbstractHandler.filter(request, response);
        return response;
    }
}